<template>
  <div class="map-container">
    <div class="page-header">
      <h2>博物馆地图管理</h2>
      <el-button type="primary" @click="handleAdd">
        添加地图
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="地图名称">
          <el-input v-model="searchForm.name" placeholder="请输入地图名称" clearable />
        </el-form-item>
        <el-form-item label="楼层">
          <el-select v-model="searchForm.floor" placeholder="请选择楼层" clearable class="filter-select">
            <el-option label="一楼" value="F1" />
            <el-option label="二楼" value="F2" />
            <el-option label="三楼" value="F3" />
            <el-option label="四楼" value="F4" />
            <el-option label="五楼" value="F5" />
            <el-option label="六楼" value="F6" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="filter-select">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="地图名称" />
        <el-table-column prop="floor" label="楼层" width="100">
          <template #default="{ row }">
            {{ 
              row.floor === 'F1' ? '一楼' : 
              row.floor === 'F2' ? '二楼' : 
              row.floor === 'F3' ? '三楼' : 
              row.floor === 'F4' ? '四楼' : 
              row.floor === 'F5' ? '五楼' : '六楼'
            }}
          </template>
        </el-table-column>
        <el-table-column label="地图图片" width="180">
          <template #default="{ row }">
            <el-image
              v-if="row.imageUrl"
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              class="map-image"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button 
                :type="row.status === 1 ? 'warning' : 'success'" 
                link 
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加地图' : '编辑地图'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="地图名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入地图名称" />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-select v-model="formData.floor" placeholder="请选择楼层">
            <el-option label="一楼" value="F1" />
            <el-option label="二楼" value="F2" />
            <el-option label="三楼" value="F3" />
            <el-option label="四楼" value="F4" />
            <el-option label="五楼" value="F5" />
            <el-option label="六楼" value="F6" />
          </el-select>
        </el-form-item>
        <el-form-item label="地图图片" prop="imageUrl">
          <el-upload
            class="map-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="customUpload"
          >
            <img v-if="formData.imageUrl" :src="formData.imageUrl" class="map-image" />
            <el-icon v-else class="map-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            支持 jpg/png 文件，建议尺寸 1920x1080
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入地图描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getMapPage, 
  addMap, 
  updateMap, 
  removeMap,
  updateMapStatus 
} from '@/api/map'

// 搜索表单
const searchForm = ref({
  name: '',
  floor: '',
  status: ''
})

// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const formData = ref({
  id: '',
  name: '',
  floor: '',
  imageUrl: '',
  description: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入地图名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  floor: [
    { required: true, message: '请选择楼层', trigger: 'change' }
  ],
  imageUrl: [
    { required: true, message: '请上传地图图片', trigger: 'change' }
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 获取地图列表
const fetchMaps = async () => {
  loading.value = true
  try {
    const params = {
      current: page.value.current,
      size: page.value.size,
      name: searchForm.value.name,
      floor: searchForm.value.floor,
      status: searchForm.value.status
    }
    const res = await getMapPage(params)
    tableData.value = res.records
    page.value.total = res.total
  } catch (error) {
    ElMessage.error('获取地图列表失败')
  } finally {
    loading.value = false
  }
}

// 图片上传前的验证
const beforeUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 自定义上传方法
const customUpload = async (options) => {
  try {
    // 这里实现文件上传逻辑
    const reader = new FileReader()
    reader.readAsDataURL(options.file)
    reader.onload = (e) => {
      formData.value.imageUrl = e.target.result
    }
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 搜索
const handleSearch = () => {
  page.value.current = 1
  fetchMaps()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    name: '',
    floor: '',
    status: ''
  }
  handleSearch()
}

// 添加
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = {
    id: '',
    name: '',
    floor: '',
    imageUrl: '',
    description: '',
    status: 1
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addMap(formData.value)
          ElMessage.success('添加成功')
        } else {
          await updateMap(formData.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchMaps()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    await updateMapStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success('状态更新成功')
    fetchMaps()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这个地图吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await removeMap(row.id)
      ElMessage.success('删除成功')
      fetchMaps()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  page.value.size = val
  fetchMaps()
}

// 当前页改变
const handleCurrentChange = (val) => {
  page.value.current = val
  fetchMaps()
}

// 初始化
fetchMaps()
</script>

<style scoped>
.map-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.map-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 169px;
}

.map-uploader:hover {
  border-color: #409EFF;
}

.map-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 169px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-image {
  width: 300px;
  height: 169px;
  display: block;
  object-fit: cover;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.filter-select {
  width: 180px;  /* 设置选择框宽度 */
}
</style> 